import java.util.ArrayList;
import java.util.List;

public class SpiralOrder {
    // leetcode 螺旋矩阵
    // https://leetcode.cn/problems/spiral-matrix/description/?envType=study-plan-v2&envId=top-100-liked
    public List<Integer> spiralOrder(int[][] matrix) {
        int len1 = matrix.length, len2 = matrix[0].length;
        int top = 0, bottom = len1-1, left = 0, right = len2-1;
        List<Integer> ret = new ArrayList<>();
        while (true) {
            for (int j = left; j <= right; j++) {
                ret.add(matrix[top][j]);
            }
            if (++top > bottom) break;
            for (int i = top; i <= bottom; i++) {
                ret.add(matrix[i][right]);
            }
            if (--right < left) break;
            for (int j = right ; j >= left; j--) {
                ret.add(matrix[bottom][j]);
            }
            if(--bottom < top) break;
            for (int i = bottom; i >= top; i--) {
                ret.add(matrix[i][left]);
            }
            if(++left > right) break;
        }
        return ret;
    }
}
